﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DataShow
{
    public partial class XunYue : System.Web.UI.Page
    {
        protected string IndexUrl = "/Index.aspx";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Convert.ToBoolean(Session["isadmin"]) == false)
            {
                IndexUrl = "ForecasterIndex.aspx";
            }
            this.anp.PageSize = Convert.ToInt32(ConfigurationManager.AppSettings["pagesize"]);
            if (!IsPostBack)
            {
                Search("");
            }
        }

        protected void btn_search_all_Click(object sender, EventArgs e)
        {
            
        }

        #region 搜索方法
        /// <summary>
        /// 搜索方法
        /// </summary>
        /// <param name="month">月份</param>
        private void Search(string month)
        {
            string sql = "",condition="";
            if (string.IsNullOrEmpty(month))
            {
                sql = string.Format("select * from XunYue");
            }
            else
            {
                sql = string.Format("select * from XunYue where [month]='{0}'", month);
                condition = "[month]='" + month + "'";
            }
            int pagesize = anp.PageSize;
            int pageindex = anp.CurrentPageIndex;
            anp.RecordCount = new codeDAL.SqlHelper().ExecuteQuery(sql, CommandType.Text).Rows.Count;
            gv_result.DataSource = new codeDAL.Common().Search("XunYue", pagesize, pageindex, condition, "*","id,month");
            gv_result.DataBind();
            if (anp.RecordCount == 0)
            {
                gv_result.Visible = false;
                anp.Visible = false;
                div_nodata.Visible = true;
            }
            else
            {
                gv_result.Visible = true;
                anp.Visible = true;
                div_nodata.Visible = false;
            }
        } 
        #endregion

        #region 全选
        /// <summary>
        /// 全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_check_all_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow item in gv_result.Rows)
            {
                (item.FindControl("Select") as CheckBox).Checked = true;
            }
        } 
        #endregion

        #region 删除选中
        /// <summary>
        /// 删除选中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_deleete_checked_Click(object sender, EventArgs e)
        {
            CheckBox cb = null;
            Label lbl_id = null;
            string sql = "delete from xunyue where id=";
            codeDAL.SqlHelper sqlhelper = new codeDAL.SqlHelper();
            foreach (GridViewRow item in gv_result.Rows)
            {
                cb = item.FindControl("Select") as CheckBox;
                if (cb.Checked)
                {
                    lbl_id = item.FindControl("ID") as Label;
                    string exesql = sql + lbl_id.Text.Trim();
                    
                    sqlhelper.ExecuteNonQuery(exesql, null);
                }
            }
            if (anp.CurrentPageIndex == anp.PageCount)
            {
                anp.CurrentPageIndex = 1;
            }
            Search("");
        } 
        #endregion

        #region 翻页
        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void anp_PageChanged(object sender, EventArgs e)
        {
            if (cbx_by_month.Checked)
            {
                Search(ddl_month_search.SelectedValue);
            }
            else
            {
                Search("");
            }
        } 
        #endregion

        #region 存储数据
        /// <summary>
        /// 存储数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_save_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            
            string month = ddl_month.SelectedValue;
            string type = ddl_type.SelectedValue;
            string content = txt_content.Text;
            if (string.IsNullOrEmpty(content) )
            {
                Common.RegisterScriptAtPageLast(Page, "alert('内容不能为空！')");
                return;
            }
            if (xy_type.Value == "modify")
            {
                var id = ID.Value;
                string sql = string.Format("update xunyue set month='{0}',[xun]='{1}',[content]='{2}' where id={3}", month,type,content,id);
                try
                {
                    new codeDAL.SqlHelper().ExecuteNonQuery(sql, null);
                    Common.RegisterScriptAtPageLast(Page, "alert('修改成功！')");
                }
                catch
                {
                    Common.RegisterScriptAtPageLast(Page, "alert('修改失败！')");
                }
                cbx_by_month.Checked = false;
                Search("");
                return;
            }
            //检查是不是已经有这个询月
            string sqlcheck = string.Format("delete from xunyue where [month]='{0}' and xun='{1}'", month, type);
            new codeDAL.SqlHelper().ExecuteNonQuery(sqlcheck, null);
            bool result = Save(month, type, content);
            if (result)
            {
                Common.RegisterScriptAtPageLast(Page, "alert('添加成功！')");
            }
            else
            {
                Common.RegisterScriptAtPageLast(Page, "alert('后台错误！')");
            }
            txt_content.Text = "";
            cbx_by_month.Checked = false;
            Search("");
        } 
        #endregion

        #region 存储公共方法
        /// <summary>
        /// 存储公共方法
        /// </summary>
        /// <param name="month"></param>
        /// <param name="type"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        private bool Save(string month, string type, string content)
        {
            string sql = string.Format("insert into XunYue values('{0}','{1}','{2}')", month, type, content);
            return new codeDAL.SqlHelper().ExecuteNonQuery(sql, null) > 0;
        } 
        #endregion

        #region 按月份搜索
        /// <summary>
        /// 按月份搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_search_Click(object sender, EventArgs e)
        {
            if (cbx_by_month.Checked)
            {
                Search(ddl_month_search.SelectedValue);
            }
            else
            {
                Search("");
            }
        } 
        #endregion

        /// <summary>
        /// 编辑条目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_edit_Click(object sender, EventArgs e)
        {
            var id = (sender as LinkButton).CommandArgument;
            string sql = "select * from xunyue where id=" + id;
            try
            {
                DataTable dt = new codeDAL.SqlHelper().ExecuteQuery(sql, CommandType.Text);
                DataRow row = dt.Rows[0];
                Common.RegisterScriptAtPageLast(Page, string.Format("CallModal({0},'{1}','{2}','{3}')", id, row["month"].ToString(), row["xun"].ToString(), row["content"].ToString()));
            }
            catch
            {
                Common.RegisterScriptAtPageLast(Page, "alert('找不到这个条目')");
            }
        }

        protected string GetXun(string input)
        {
            switch (input)
            {
                case "00":return "整月";
                case "01": return "上旬";
                case "02": return "中旬";
                case "03": return "下旬";
                default: return "";
            }
        }

        protected void btn_import_Click(object sender, EventArgs e)
        {
            //检查是否有文件
            if (file.HasFile)
            {
                string filename = file.FileName;
                filename = Path.GetFileNameWithoutExtension(filename);
                string fmonth = filename.Substring(0, 2);
                byte[] contentByte = file.FileBytes;
                string fcontent = Encoding.Default.GetString(contentByte);
                string ftype = "";
                try
                {
                    ftype = filename.Substring(2, 2);
                }
                catch
                {
                    ftype = "00";
                }
                Save(fmonth, ftype, fcontent);
            }
            cbx_by_month.Checked = false;
            Search("");
        }

        protected void gv_result_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.Cells.Count != 6)
            {
                return;
            }
            e.Row.Cells[0].Width = 10;
            e.Row.Cells[1].Width = 10;
            e.Row.Cells[2].Width = 10;
            e.Row.Cells[3].Width = 10;
            e.Row.Cells[4].Width = 1000;
            e.Row.Cells[5].Width = 10;
        }

        
    }
}